package com.dj.dormitory.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.dormitory.commonutils.BCPEUtils;
import com.dj.dormitory.commonutils.Result;

import com.dj.dormitory.entity.*;
import com.dj.dormitory.entity.excel.StuDataExcel;

import com.dj.dormitory.entity.req.StuReq;
import com.dj.dormitory.entity.vo.StuVo;
import com.dj.dormitory.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DJ同学
 * @since 2021-01-24
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserService userService;

    @Autowired
    private SelectionDormitoryService selectionDormitoryService;

    @Autowired
    private DormitoryService dormitoryService;

    @Autowired
    private DormitoryStudentService dormitoryStudentService;

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private SelectionService selectionService;

    @RequestMapping("/getAll")
    public Result getAll(){
        List<StuVo>  stus = studentService.getAll();
        return Result.ok().data("stus",stus);
    }

   //条件分页查询
    @PostMapping("/list")
   public Result getList(@RequestBody StuReq stuReq){
        if(stuReq.getKey()!=null&&stuReq.getKey().length()==0) stuReq.setKey(null);
        Map<String, Object> map = studentService.getList(stuReq);
        return Result.ok().data("stus",map.get("stus")).data("count",map.get("count"));
   }

   @PostMapping("/edit")
   public Result edit(@RequestBody StuVo stuVo){
       //修改user和stu
       try{
           User user = new User();
           user.setId(stuVo.getUserId());
           user.setUserName(stuVo.getUsername());
           user.setPassword(stuVo.getPassword());
           user.setName(stuVo.getName());
           user.setPhone(stuVo.getPhone());
           user.setRemark(stuVo.getRemark());
           userService.updateById(user);

           Student stu = new Student();
           stu.setId(stuVo.getId());
           stu.setIdcard(stuVo.getIdcard());
           stu.setSex(stuVo.getSex());
           stu.setGradeId(stuVo.getGradeId());
           stu.setClassId(stuVo.getClassId());
           studentService.updateById(stu);
           return Result.ok().message("修改学生信息成功");
       }catch (Exception e){
           e.printStackTrace();
           return Result.error().message("修改学生信息失败");
       }
   }
    @PostMapping("/add")
    public Result add(@RequestBody StuVo stuVo){
        //判断选择的是否是班级
        Org org = orgService.getById(stuVo.getClassId());
        if(org.getType()!=4){
            return Result.error().message("请选择班级，才可以哦");
        }
        //修改user和stu
        User user = new User();
        user.setUserName(stuVo.getUsername());
        //加密
        user.setPassword(BCPEUtils.encode(stuVo.getPassword()));
        user.setName(stuVo.getName());
        user.setPhone(stuVo.getPhone());
        user.setType(2);
        user.setRemark(stuVo.getRemark());
        userService.save(user);

        Student stu = new Student();
        stu.setUserId(user.getId());
        stu.setSno(stuVo.getSno());
        stu.setIdcard(stuVo.getIdcard());
        stu.setSex(stuVo.getSex());
        stu.setGradeId(stuVo.getGradeId());
        stu.setClassId(stuVo.getClassId());
        try{
            boolean save = studentService.save(stu);
            return save ? Result.ok().message("添加学生成功"):Result.error().message("添加学生失败");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error().message("添加学生失败");
        }
    }

    @DeleteMapping("/deleteOne/{userId}/{id}")
    public Result edit(@PathVariable(value = "userId") String userId,@PathVariable(value = "id") String id){
        userService.removeById(Integer.parseInt(userId));
        studentService.removeById(Integer.parseInt(id));
        return Result.ok().message("删除学生信息成功");
    }
    @DeleteMapping("/deletePart/{userIdsStr}/{stuIdsStr}")
    public Result deletePart(@PathVariable("userIdsStr")List<String> userIds,@PathVariable("stuIdsStr")List<String> ids){
        userService.removeByIds(userIds);
        studentService.removeByIds(ids);
        return  Result.ok().message("批量删除学生信息成功");
    }
    @GetMapping("/exportAll")
    public Result exportAll(HttpServletResponse response) throws IOException {
        List<StuDataExcel> listExcel = new ArrayList<>();
        List<StuVo>  stus = studentService.getAll();
        for(int i = 0;i<stus.size();i++){
            StuDataExcel dataExcel = new StuDataExcel();
            BeanUtils.copyProperties(stus.get(i),dataExcel);
            if(stus.get(i).getSex()!=null){
                switch (stus.get(i).getSex()){
                    case 0:
                        dataExcel.setSexStr("女");
                        break;
                    case 1:
                        dataExcel.setSexStr("男");
                        break;
                }
            }
            listExcel.add(dataExcel);
        }
        String fileName = new String("学生信息.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/msexcel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName );
        EasyExcel.write(response.getOutputStream(), StuDataExcel.class)
                .sheet("sheet")
                .doWrite(listExcel);
        return Result.ok().message("下载成功");
    }

//    根据userId获得学生信息
    @PostMapping("/getOne")
    public Result getOneByUserId(HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("userId");
        StuVo stuVo = studentService.getOneByUserId(userId);
        System.out.println(stuVo);
        return Result.ok().data("stu",stuVo);
    }
    //选择宿舍
    @GetMapping("/selectDormitory")
    public Result SelectDormitory(HttpServletRequest request){
        //根据学生id,获得学生class_id
        Student studentId = studentService.getById((Integer) request.getAttribute("studentId"));
        int classId = studentId.getClassId();
        int gradeId = studentId.getGradeId();
        //获得选择的时间范围
        QueryWrapper<Selection> selectionQueryWrapper = new QueryWrapper<>();
        selectionQueryWrapper.eq("class_id",classId);
        selectionQueryWrapper.eq("grade_id",gradeId);
        List<Selection> selection = selectionService.list(selectionQueryWrapper);
        if(selection==null||selection.size()==0){
            return Result.error().message("在线选宿舍未开放，请联系宿管员");
        }
        LocalDate startTime = selection.get(0).getStartTime();
        LocalDate endTime = selection.get(0).getEndTime();
        LocalDate now = LocalDate.now();
        //判断当前时间是否在区间
        if(now.isBefore(startTime)||now.isAfter(endTime)){
            return Result.error().message("操作失败，不在时间段内选择。["+startTime+","+endTime+"]");
        }
        //获得待选宿舍 根据学生所在的班级id tb_selection_dormitory
        QueryWrapper<SelectionDormitory> selectionDormitoryQueryWrapper = new QueryWrapper<>();
        selectionDormitoryQueryWrapper.eq("class_id",classId);
        selectionDormitoryQueryWrapper.eq("grade_id",gradeId);
        List<SelectionDormitory> list = selectionDormitoryService.list(selectionDormitoryQueryWrapper);

        List<Map<String,Object>> res =  new ArrayList<>();
        for(SelectionDormitory one:list){
            Dormitory dormitory = dormitoryService.getById(one.getDormitoryId());
            HashMap<String,Object> map = new HashMap<>();
            //宿舍Id
            int dormitoryId =dormitory.getId();
            map.put("dormitoryId",dormitoryId);
            //楼名
            Building building = buildingService.getById(dormitory.getBuildingId());
            String buildingName = building.getName();
            map.put("buildingName",buildingName);
            //宿舍号
            int dormitoryNo =dormitory.getNo();
            map.put("dormitoryNo",dormitoryNo);
            //当前宿舍的容量roomSize
            Integer roomSize = dormitoryService.getRoomSize(one.getDormitoryId());
            map.put("roomSize",roomSize);
            QueryWrapper<DormitoryStudent> dormitoryStudentQueryWrapper = new QueryWrapper<>();
            dormitoryStudentQueryWrapper.eq("dormitory_id",one.getDormitoryId());
            int selectedSize = dormitoryStudentService.count(dormitoryStudentQueryWrapper);

            //选择宿舍的学生 studentList （stuName bid ）By domitoryId
            List<Map<String,Object>> studentList = new ArrayList<>();
            List<DormitoryStudent> dormitoryStudents = dormitoryStudentService.list(dormitoryStudentQueryWrapper);
            for(DormitoryStudent dormitoryStudent:dormitoryStudents){
                Map<String,Object> map1 = new HashMap<>();
                map1.put("bedId",dormitoryStudent.getBedId());
                //查找学生学号
                Student student = studentService.getById(dormitoryStudent.getStudentId());
                map1.put("studentSNo",student.getSno());
                map1.put("studentId",student.getId());
                studentList.add(map1);
            }
            map.put("studentList",studentList);
            //剩余容量
            int unSelectedSize  =roomSize - dormitoryStudents.size();
            map.put("unSelectedSize",unSelectedSize);
            res.add(map);
        }
        return Result.ok().data("data",res).message("预选时间范围：["+startTime+","+endTime+"]");
    }

}

